package org.sith.taskrunner.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.sith.taskrunner.api.toolkit.TaskToolkit;
import org.sith.taskrunner.ejb.TaskManagerHelper;
import org.sith.taskrunner.ejb.exceptions.EJBServiceExecutionException;
import org.sith.taskrunner.ejb.exceptions.ToolkitNotFoundException;
import org.sith.taskrunner.ejb.services.WebTaskExecutorService;
import org.sith.taskrunner.ejb.transformers.StringResult;


public class EJBServlet extends HttpServlet {

    @EJB(name = "WebTaskExecutorServiceEJB")
    WebTaskExecutorService webTaskExecutorService;  


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String name = request.getParameter("taskname");
        String data = request.getParameter("data");
        TaskToolkit taskToolkit;
        PrintWriter writer;
        String acceptEncoding = request.getHeader("accept-encoding");
		if((acceptEncoding!=null)&&(acceptEncoding.indexOf("gzip")!=-1)){
			writer = new PrintWriter(new GZIPOutputStream(response.getOutputStream()), false);
			response.setHeader("content-encoding", "gzip");
		}else{
			writer = response.getWriter();
		}
        try {
            taskToolkit = TaskManagerHelper.getInstance().getToolkit(name);
            StringResult stringResult = webTaskExecutorService.makeTask(taskToolkit, data);
            writer.println(stringResult.getResult());
        } catch (ToolkitNotFoundException e) {
            writer.println(e.getMessage());
        } catch (EJBServiceExecutionException e) {            
            writer.println(e.getMessage());
        }
        writer.close();
    }
}
